/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gossipinator;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.microedition.rms.*;

/**
 *
 * @author cox
 */
public class RecStorage implements IStorage {

        private static final String storeName="GS2";
        private static RecordStore rs=null;
        private static RecordEnumeration recordEnumeration = null;
        private static int numrec;
    
        public boolean init(){
            
             try {
                rs= RecordStore.openRecordStore(storeName,true);

                if ( rs == null) {
                    return false;
                }
                recordEnumeration = rs.enumerateRecords(null, null, false);
                numrec = rs.getNumRecords();
                System.out.println("Numrecs: " +numrec+"\n");
                return true;
             } catch(Exception e) {
                System.out.println(e);
             }
             return false;
        }

        public boolean deinit(){
            try {
                numrec = rs.getNumRecords();
                System.out.println("Deinit: Numrecs: " +numrec+"\n");
                rs.closeRecordStore();
            } catch(Exception e) {
                System.out.println(e);
            }
            return true;
        }

        public boolean hasnext(){
               return recordEnumeration.hasNextElement();
        }

        public ByteArrayInputStream read(){
            byte[] byteInputData = new byte[300];
            ByteArrayInputStream inputStream = new ByteArrayInputStream(byteInputData);

            try {
                    rs.getRecord(recordEnumeration.nextRecordId(), byteInputData, 0);
                    inputStream = new ByteArrayInputStream(byteInputData);   
            } catch(Exception e) {
                System.out.println(e);
            }
            return inputStream;
        }

        public boolean write(ByteArrayOutputStream outputStream,int index){

            byte[] outputRecord;

            try {
                outputRecord = outputStream.toByteArray();
                //Adding record to record store
                rs.addRecord(outputRecord,0,outputRecord.length);
                recordEnumeration.rebuild();
            } catch(Exception e) {
                System.out.println(e);
            }
            return true;
        }
        
        public int count(){
            return numrec;
        }
}
